package com.atguigu.servlet;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取下载文件名
        String downloadFileName="456.png";
        //读取下载文件的对象内容
        ServletContext servletContext = getServletContext();
        InputStream resourceAsStream = servletContext.getResourceAsStream("/file/"+downloadFileName);
        //获取要下载文件的类型
        String mimeType = servletContext.getMimeType("/file/" + downloadFileName);
        System.out.println("下载的文件类型："+mimeType);
        //回传前通过响应头，告诉客户端要回传的数据类型
        resp.setContentType(mimeType);
        //告诉客户端收到的数据，用于下载
        resp.setHeader("Content-Disposition", "attachment; fileName="+downloadFileName);
        //获取响应输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        //将输入流中的数据复制到输出流
        IOUtils.copy(resourceAsStream,outputStream);


    }
}
